<?php 
	require_once 'clases/posiMovil.php';
	session_start(); ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--
//  Copyright (C) 2004-2006  Autodesk, Inc.
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of version 2.1 of the GNU Lesser
//  General Public License as published by the Free Software Foundation.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
-->
<html>

<head>

<?php include("config.php");
      include("utils.php");
	  include(ROOT_DIR_CLASES.'/cCliente.php');
?>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
    <meta http-equiv="content-script-type" content="text/javascript">
    <meta http-equiv="content-style-type" content="text/css">
    <link href="<?php echo ESTILO?>/globalStyles.css" rel="stylesheet" type="text/css">
	<link href="<?php echo ESTILO?>/otherStyles.css" rel="stylesheet" type="text/css">
	<link href="<?php echo ESTILO?>/viewer.css" rel="stylesheet" type="text/css">
	<link href="<?php echo ESTILO?>/bykom.css" rel="stylesheet" type="text/css">

    
</head>

<body onLoad="OnPageLoad()"> 

	
<?php
//ini_set("display_errors","1");
    //error_reporting(E_ALL);
require_once('../common.php');
require_once($webExtensionsDirectory . 'www/mapviewerphp/layerdefinitionfactory.php');	
require_once('layer_functions.php');

try
{
	//---------------------------------------------------//
		$cuentaSelectSegui = $_SESSION['cuentaSelectSegui']; // cuenta para seguir (-1 si no selecciono)
		$latitudSegui  = "";
		$longitudSegui = "";
		$hayPosiActual = false;
		$changeColor = false;
		//---------------------------------------------------//   	    
   			// Initialize
    		MgInitializeWebTier($webconfigFilePath);
    		$sessionId = ($_SERVER['REQUEST_METHOD'] == "POST")?$_POST['SESSION']: $_GET['SESSION'];
    		$userInfo = new MgUserInformation($sessionId);
    		$siteConnection = new MgSiteConnection();
   	 		$siteConnection->Open($userInfo);
    		$resourceService = $siteConnection->CreateService(MgServiceType::ResourceService);
    		$featureService = $siteConnection->CreateService(MgServiceType::FeatureService);      
		
   		//---------------------------------------------------//
    		// Open the map
    		$map = new MgMap();
    		$map->Open($resourceService, AVL_MAP);
    		
		
	
    if (isset($_SESSION['posicionesImprimibles']))
	{
		$aux = $_SESSION['posicionesImprimibles'];
		foreach ($aux as $posiMovil) 
       	{ 
       		if ($posiMovil->tienePosicionActual > 0)
       		{
       		$cuenta =  $posiMovil->id;
        	if ($cuenta == $cuentaSelectSegui)
        	{
        		$latitudSegui = $posiMovil->latitud;
        		$longitudSegui = $posiMovil->longitud;	
        		$hayPosiActual = true;
        		$changeColor = true;
        	}
    		//---------------------------------------------------//
    		// Create a feature source with point data.
    		// (The Sheboygan sample data does not contain such data,
    		// so we'll create it.)
            $name = "Points".$cuenta;
			$classDefinition = getPointClassDefinition($name);
			$featureSchema = new MgFeatureSchema("PointSchema", "Point schema");
			$featureSchema->GetClasses()->Add($classDefinition);             
			$featureSourceName = "Session:$sessionId//".$name.".FeatureSource";
			$resourceIdentifier = new MgResourceIdentifier($featureSourceName);
			$wkt = "LOCALCS[\"*XY-MT*\",LOCAL_DATUM[\"*X-Y*\",10000],UNIT[\"Meter\", 1],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH]]";
			$sdfParams = new MgCreateSdfParams("ArbitraryXY", $wkt, $featureSchema);
   			$featureService->CreateFeatureSource($resourceIdentifier, $sdfParams);
			$batchPropertyCollection = new MgBatchPropertyCollection();
			$wktReaderWriter = new MgWktReaderWriter();
			$agfReaderWriter = new MgAgfReaderWriter();
			$geometryFactory = new MgGeometryFactory();
			$propertyCollection = MakePointCar($posiMovil->movil, $posiMovil->descripcion, $posiMovil->identificador, $posiMovil->marca, $posiMovil->modelo, $posiMovil->patente, $posiMovil->longitud, $posiMovil->latitud, $posiMovil->fechaMensaje, $posiMovil->direccionAbrev, $posiMovil->satelites, $posiMovil->sentidoPalabra, $posiMovil->velocidad, $posiMovil->evento);
			
			$batchPropertyCollection->Add($propertyCollection);
			unset($propertyCollection);	

			$cmd = new MgInsertFeatures($name, $batchPropertyCollection); 
			$featureCommandCollection = new MgFeatureCommandCollection();
			$featureCommandCollection->Add($cmd);
	
			$featureService->UpdateFeatures($resourceIdentifier, $featureCommandCollection, false);    
    		//*******************************************************************
    		// Create a new layer icon movil
    		$factory = new LayerDefinitionFactory();
    		// Create a mark symbol
    		$resourceId = AVL_SYMBOLS;
    		$symbolName = $posiMovil->imagenVehiculo;
    		
    		$width = '45';  // unit = points
    		$height = '45'; // unit = points
    		($changeColor)? $color = 'FF'.COLOR_POSI_ACTUAL_SEGUI : $color = 'FF'.COLOR_POSI_ACTUAL;
    		$markSymbol = $factory->CreateMarkSymbol($resourceId, $symbolName, $width, $height, $color);   
    
    		// Create a text symbol
    		$text = "IDENTIFICADOR";
    		$fontHeight = FONTSIZE_LEGEND_MOVIL;
    		($changeColor)?$foregroundColor = COLOR_LEGEND_MOVIL_SEGUIMIENTO : $foregroundColor = COLOR_LEGEND_MOVIL;
    		$textSymbol = $factory->CreateTextSymbol($text, $fontHeight, $foregroundColor);

    		// Create a point rule.
    		$legendLabel = 'trees';
    		$filter = '';
    		$pointRule = $factory->CreatePointRule($legendLabel, $filter, $textSymbol, $markSymbol);
      
    		// Create a point type style.
    		$pointTypeStyle = $factory->CreatepointTypeStyle($pointRule);
      
    		// Create a scale range.
    		$minScale = '0';
    		$maxScale = '1000000000000';
    		$pointScaleRange = $factory->CreateScaleRange($minScale, $maxScale, $pointTypeStyle);      

    		// Create the layer definiton.
    		$featureName = 'PointSchema:'.$name;
    		$geometry = 'GEOM';
    		$layerDefinition = $factory->CreateLayerDefinition($featureSourceName, $featureName, $geometry, $pointScaleRange);
    		//---------------------------------------------------//
    		// Add the layer to the map
    		$newLayer = add_layer_definition_to_map($layerDefinition, $name, "Posicion actual", $sessionId, $resourceService, $map, true);
    		//file_put_contents("c:\\hola2.xml", $newLayer);
    		add_layer_to_group($newLayer, $posiMovil->identificador, $posiMovil->identificador, $map);

    		// --------------------------------------------------//
    		$layerCollection = $map->GetLayers();
    		if ($layerCollection->Contains($name))
    		{
        		$pointsLayer = $layerCollection->GetItem($name);
        		$pointsLayer->SetVisible(true);
    		}
        	} 
       	}
        	
        }	
			//---------------------------------------------------//
    		//  Save the map back to the session repository
    		$sessionIdName = "Session:$sessionId//".AVL_MAP.".Map";
    		$sessionResourceID = new MgResourceIdentifier($sessionIdName);
			$sessionResourceID->Validate();
    		$map->Save($resourceService, $sessionResourceID);
    //---------------------------------------------------//
}
catch (MgException $e)
{
	echo "<script language=\"javascript\" type=\"text/javascript\"> \n";
	echo "    alert(\" " . $e->GetMessage() . " \"); \n";
	echo "</script> \n";
}

///////////////////////////////////////////////////////////////////////////////////
?>
<script language="javascript" type="text/javascript">
	function OnPageLoad()
        {
        	parent.mapFrame.Refresh();
            var scale = parent.mapFrame.GetScale();
            <?php if ($hayPosiActual && $_SESSION['hizoZoom'] == 0) { 
            	$_SESSION['hizoZoom'] = 1; ?>
            	scale = <?=ZOOM_AVL?>;
            <?php } ?>	
            
            <?php
            if ($hayPosiActual) { ?>
            	parent.mapFrame.ZoomToView(<?= $longitudSegui ?>, <?= $latitudSegui ?>, scale, true);
            <?php }?>	
        }
    </script>
</body>
</html>


